package com.lb.myeam.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import com.alibaba.fastjson.JSONObject;
import com.lb.myeam.common.utils.DateUtil;
import com.lb.myeam.common.utils.StringUtil;
import com.lb.myeam.core.dao.TeamDao;
import com.lb.myeam.core.dao.UserDao;
import com.lb.myeam.core.dao.impl.TeamDaoImpl;
import com.lb.myeam.core.dao.impl.UserDaoImpl;
import com.lb.myeam.core.entity.TeamEntity;
import com.lb.myeam.core.entity.UserEntity;

public class UserServlet extends HttpServlet {

	private UserDao userDao = new UserDaoImpl();
	private TeamDao teamDao = new TeamDaoImpl();

	// get
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	// post
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String act = req.getParameter("act");
		System.out.println("act:"+act);
		if ("login".equals(act)) {
			doLogin(req, resp);
		} else if ("doPreAdd".equals(act)) {
			doPreAdd(req, resp);
		} else if ("add".equals(act)) {
			doAdd(req, resp);
		} else if ("doQuery".equals(act)) {
			doQuery(req, resp);
		} else if ("delete".equals(act)) {
			doDelete(req, resp);
		} else if ("list4easyui".equals(act)) {
			doList4easyui(req, resp);
		} else if ("checkLogin".equals(act)) {
			checkLogin(req, resp);
		}

	}

	public void doLogout(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// session
		req.getSession().invalidate();
		Cookie[] cookies = req.getCookies();
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			cookie.setMaxAge(0);
		}

	}

	public void doLogin(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String account = req.getParameter("account");
		String password = req.getParameter("password");
		//input:code
		String checkcode = req.getParameter("checkcode").toUpperCase();
		//produce:code
		String piccode = (String) req.getSession().getAttribute("piccode");

		UserEntity user = userDao.login(account, password);
		if (null != user) {
			if (checkcode.equals(piccode)) {
				System.out.println("验证码对");
				req.getSession().setAttribute("user_online", user);
				resp.sendRedirect("../pages/user/main.jsp");
			} else {
				System.out.println("验证码错");
				req.setAttribute("error_msg", "登录失败");
				req.getRequestDispatcher("../pages/login.jsp").forward(req,
						resp);
			}
		} else {
			req.setAttribute("error_msg", "登录失败");
			req.getRequestDispatcher("../pages/login.jsp").forward(req, resp);
		}

		// String account = req.getParameter("account");
		// String password = req.getParameter("password");
		//
		// UserEntity user = userDao.login(account, password);
		// if (null != user) {
		// if (true) {
		// System.out.println(user.getId());
		// Cookie cookie = new Cookie("userId", user.getId());
		// cookie.setMaxAge(20000000);
		// resp.addCookie(cookie);
		// }
		//
		// req.getSession().setAttribute("user_online", user);
		// resp.sendRedirect("../pages/user/main.jsp");
		// } else {
		// req.setAttribute("error_msg", "login fial...");
		// req.getRequestDispatcher("../pages/login.jsp").forward(req, resp);
		// }

	}

	// add
	public void doAdd(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("go to servlet doAdd");
		String account = req.getParameter("account");
		String name = req.getParameter("name");
		String email = req.getParameter("email");
		String sex = req.getParameter("sex");
		String birthday = req.getParameter("birthday");
		String address = req.getParameter("address");
		String teamId = req.getParameter("teamId");
		String password = req.getParameter("password");

		UserEntity user = new UserEntity();
		user.setAccount(account);
		user.setName(name);
		user.setEmail(email);
		user.setSex(sex);
		user.setBirthday(DateUtil.str2Date(birthday));
		user.setTeamId(teamId);
		user.setPassword(password);
		user.setAddress(address);
		userDao.add(user);
		doQuery(req, resp);

	}

	// preAdd
	public void doPreAdd(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("go to servlet doPreAdd");
		List<TeamEntity> teamList = teamDao.query();
		resp.setContentType("text/html;charset=utf-8");
		String str = JSONArray.fromObject(teamList).toString();
		System.out.println(str);
		resp.getWriter().write(str);

	}

	// qurey
	public void doQuery(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("go to servlet doQuery");
		List<UserEntity> userList = userDao.query();
		System.out.println(userList);
		req.setAttribute("userList", userList);
		req.getRequestDispatcher("../pages/user/user_list.jsp").forward(req,
				resp);

	}

	// update
	public void doUpdate(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("go to servlet doUpdate");
		String id = req.getParameter("id");
		String account = req.getParameter("account");
		String email = req.getParameter("email");
		String sex = req.getParameter("sex");
		Date birthday = new Date();
		String address = req.getParameter("address");
		String teamId = req.getParameter("teamId");
		String password = req.getParameter("password");
		String name = req.getParameter("name");

		UserEntity user = new UserEntity(id, account, email, sex, birthday,
				address, teamId, password, name);
		userDao.update(user);
		req.getRequestDispatcher("../pages/user/user_update.jsp").forward(req,
				resp);

	}

	// delete
	public void doDelete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("go to servlet doDelete");
		userDao.delete(req.getParameter("id"));
		doQuery(req, resp);

	}

	public void doList4easyui(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("list4easyui");
		List<UserEntity> list = userDao.query();
		JSONObject obj = new JSONObject();

		obj.put("rows", list);
		obj.put("total", list.size());
		PrintWriter out = resp.getWriter();
		out.print(obj);
		out.flush();
		out.close();
	}

	public void checkLogin(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String val = request.getParameter("account");
		// System.out.println(val);
		PrintWriter writer = response.getWriter();

		boolean exist = userDao.isExist(val);
		if (exist) {
			writer.write("ok");
		} else {
			writer.write("error");
		}
		writer.flush();
		writer.close();

	}

}
